package com.example.parallel;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 串行执行任务示例。
 */
public class CompletableFutureExecutorDemo {
    public static void main(String[] args) {
        IntStream intStream = IntStream.range(0, 10);
        List<MyTask> tasks = intStream.mapToObj(item -> new MyTask(1)).collect(Collectors.toList());

        int N_CPU = Runtime.getRuntime().availableProcessors();
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(tasks.size(), N_CPU * 2));
        List<CompletableFuture<Integer>> futures = tasks.stream()
                .map(task -> CompletableFuture.supplyAsync(task::doWork, executor))
                .collect(Collectors.toList());

        long start = System.currentTimeMillis();
        List<Integer> results = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
        long end = System.currentTimeMillis();
        long time = (end - start) / 1000;
        System.out.println("执行" + tasks.size() + "个任务，花费时间 " + time + " 秒");
        executor.shutdown();
    }
}
